<?php
// +----------------------------------------------------------------------
// | 知识星球[基于ThinkPHP5开发]
// +----------------------------------------------------------------------
// | Copyright (c) 2018-2019 abcblockchain.io
// +----------------------------------------------------------------------
// | 后台管理使用了HisiPHP
// +----------------------------------------------------------------------
// | Author: abcblockchain.io
// +----------------------------------------------------------------------

namespace app\api\home;

use app\common\controller\Api;
use think\Db;
use app\common\model\Users as usersModel;
use app\common\model\PhoneCode;
use app\common\model\UsersCurrency as UsersCurrencyModel;
use app\common\util\Bitcoin;
use app\common\model\GroupPosts as postModel;
use app\common\model\Redpacket as redModel;
use app\common\model\RedLog as redLogModel;

class Users extends Api
{
    protected $userModel;

    public function __construct()
    {
        parent::__construct();
        $this->userModel = new usersModel();
    }

    /**
     * 用户相关接口
     *
     * author:abcblockchain.io
     *
     */


    /**
     * 注册用户
     * @author
     */
    public function regUser()
    {
        $postData = $this->requestData;
        $resVaild = $this->validate($postData, 'Users.register');
        if ($resVaild !== true) {
            $result = array(
                'status' => 0,
                'data' => 'register failed',
            );
            if ($resVaild == '1') {
                $result['code'] = 5;
            } elseif ($resVaild == '2') {
                $result['code'] = 6;
            } elseif ($resVaild == '4') {
                $result['code'] = 7;
            } elseif ($resVaild == '5') {
                $result['code'] = 8;
            } elseif ($resVaild == '6') {
                $result['code'] = 9;
            } elseif ($resVaild == '7') {
                $result['code'] = 10;
            }
            echo json_encode($result);
            exit;
        }
        $phoneCode = new PhoneCode();
        $verifiPhone = $phoneCode->verifiregCode($postData['mobile'], 1, $postData['phoneCode']);
        if (!$verifiPhone) {
            $result = array(
                'status' => 0,
                'data' => 'phoneCode wrong',
                'code' => 12,
            );
            echo json_encode($result);
            exit;
        }
        $checkInvit = $this->userModel->checkInvitCode($postData['invit']);
        if (!$checkInvit) {
            $result = array(
                'status' => 0,
                'data' => 'invitCode not exist',
                'code' => 11,
            );
        } else {
            $res = $this->userModel->register($postData);
            if ($res) {
                $cuModel = new UsersCurrencyModel();
                $cuModel->createUsersCurrency($res, 1);
                $cuModel->createUsersCurrency($res, 2);
                $result = array(
                    'status' => 1,
                    'data' => 'register success',
                    'code' => 0,
                );
            } else {
                $result = array(
                    'status' => 0,
                    'data' => 'register failed',
                    'code' => 4,
                );
            }
        }
        echo json_encode($result);
        exit;
    }

    /**
     * 登录
     * @author
     */
    public function login()
    {
        $postData = $this->requestData;
        $resVaild = $this->validate($postData, 'Users.login');
        if ($resVaild !== true) {
            $result = array(
                'status' => 0,
                'data' => 'login failed',
            );
            if ($resVaild == '1') {
                $result['code'] = 5;
            } elseif ($resVaild == '2') {
                $result['code'] = 6;
            } elseif ($resVaild == '6') {
                $result['code'] = 9;
            } elseif ($resVaild == '7') {
                $result['code'] = 10;
            }
            echo json_encode($result);
            exit;
        }

        $res = $this->userModel->login($postData['mobile'], $postData['password']);
        if ($res) {
            $result = array(
                'status' => 1,
                'data' => $res,
                'code' => 0,
            );
        } else {
            $result = array(
                'status' => 1,
                'data' => 'login failed',
                'code' => 4,
            );
        }
        echo json_encode($result);
        exit;
    }

    /**
     * 编辑用户
     * @author
     */
    public function editUsers()
    {
        $postData = $this->requestData;
        if (isset($postData['users_id']) && $postData['users_id'] > 0) {
            $res = $this->userModel->editUsers($postData['users_id'], $postData);
            if ($res) {
                $result = array(
                    'status' => 1,
                    'data' => 'edit success',
                    'code' => 0,
                );
            } else {
                $result = array(
                    'status' => 0,
                    'data' => 'edit faild',
                    'code' => 4,
                );
            }
        } else {
            $result = array(
                'status' => 0,
                'data' => 'param error',
                'code' => 1,
            );
        }
        echo json_encode($result);
        exit;
    }

    /**
     * 找回密码
     * @author
     */
    public function forgotPwd()
    {
        $postData = $this->requestData;
        $resVaild = $this->validate($postData, 'Users.forgot_pwd');
        if ($resVaild !== true) {
            $result = array(
                'status' => 0,
                'data' => 'login failed',
            );
            if ($resVaild == '1') {
                $result['code'] = 5;
            } elseif ($resVaild == '2') {
                $result['code'] = 6;
            } elseif ($resVaild == '6') {
                $result['code'] = 9;
            } elseif ($resVaild == '7') {
                $result['code'] = 10;
            }
            echo json_encode($result);
            exit;
        }
        $phoneCode = new PhoneCode();
        $verifiPhone = $phoneCode->verifiregCode($postData['mobile'], 2, $postData['phoneCode']);
        if (!$verifiPhone) {
            $result = array(
                'status' => 0,
                'data' => 'phoneCode wrong',
                'code' => 12,
            );
            echo json_encode($result);
            exit;
        }
        $res = $this->userModel->forgotPwd($postData['mobile'], $postData['password']);
        if ($res) {
            $result = array(
                'status' => 1,
                'data' => 'find success',
                'code' => 0,
            );
        } else {
            $result = array(
                'status' => 0,
                'data' => 'find faild',
                'code' => 4,
            );
        }
        echo json_encode($result);
        exit;
    }

    /**
     * 重置支付密码
     * @author
     */
    public function resetTradePwd()
    {
        $postData = $this->requestData;
        $phoneCode = new PhoneCode();
        $verifiPhone = $phoneCode->verifiregCode($postData['mobile'], 3, $postData['phoneCode']);
        if (!$verifiPhone) {
            $result = array(
                'status' => 0,
                'data' => 'phoneCode wrong',
                'code' => 12,
            );
            echo json_encode($result);
            exit;
        }
        $res = $this->userModel->resetTradePwd($postData['mobile'], $postData['tradePwd']);
        if ($res) {
            $result = array(
                'status' => 1,
                'data' => 'find success',
                'code' => 0,
            );
        } else {
            $result = array(
                'status' => 0,
                'data' => 'find faild',
                'code' => 4,
            );
        }
        echo json_encode($result);
        exit;
    }

    /**
     * 修改密码
     * @author
     */
    public function changePwd()
    {
        $postData = $this->requestData;
        if ($postData['mobile']) {
            $resVaild = $this->validate($postData, 'Users.change_pwd');
            if ($resVaild !== true) {
                $result = array(
                    'status' => 0,
                    'data' => 'change failed',
                );
                if ($resVaild == '1') {
                    $result['code'] = 7;
                } elseif ($resVaild == '2') {
                    $result['code'] = 8;
                } elseif ($resVaild == '6') {
                    $result['code'] = 9;
                } elseif ($resVaild == '7') {
                    $result['code'] = 10;
                }
                dump($resVaild);
                echo json_encode($result);
                exit;
            }
            $type = isset($postData['type']) ? $postData['type'] : 0;
            $res = $this->userModel->changePwd($postData['mobile'], $postData['oldPassword'], $postData['password'], $type);
            if ($res == -1) {
                $result = array(
                    'status' => 0,
                    'data' => 'no user',
                    'code' => 4,
                );
            } elseif ($res == -2) {
                $result = array(
                    'status' => 0,
                    'data' => 'password wrong',
                    'code' => 5,
                );
            } elseif ($res == 1) {
                $result = array(
                    'status' => 1,
                    'data' => 'change success',
                    'code' => 0,
                );
            } else {
                $result = array(
                    'status' => 0,
                    'data' => 'change failed',
                    'code' => 6,
                );
            }
        } else {
            $result = array(
                'status' => 0,
                'data' => 'param error',
                'code' => 1,
            );
        }
        echo json_encode($result);
        exit;

    }

    /**
     * 上传图片
     * @author
     */
    public function uploadHead()
    {
        $postData = $this->requestData;
        $re = $this->base64_image_content($postData['img'], 'class');
        $data = array(
            'status' => 1,
            'imgsrc' => $re,
            'code' => 0
        );
        echo json_encode($data);
        exit;
    }

    /**
     * [将Base64图片转换为本地图片并保存]
     * @param $base64_image_content [要保存的Base64]
     * @param $path [要保存的路径]
     * @return bool|string
     */
    public function base64_image_content($base64_image_content, $group)
    {
        //匹配出图片的格式
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)) {
            $type = $result[2];
            $new_file = 'upload/' . $group . '/' . date('Ymd', time()) . "/";
            if (!file_exists($new_file)) {
                //检查是否有该文件夹，如果没有就创建，并给予最高权限
                mkdir($new_file, 0755, true);
            }
            $ping_url = rand(100000, 999999) . uniqid() . ".{$type}";
            $ftp_image_upload_url = $new_file . $ping_url;

            if (file_put_contents($ftp_image_upload_url, base64_decode(str_replace($result[1], '', $base64_image_content)))) {
                return $ftp_image_upload_url;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    /**
     * 用户详情页
     * @author
     */
    public function getUserInfo()
    {
        $postData = $this->requestData;
        if (isset($postData['userId']) && $postData['userId'] > 0) {
            $userInfo = $this->userModel->userDetail($postData['userId']);
            $groupInfo = Db::name('group')->where('id', $postData['groupId'])->field('name')->find();
            $postModel = new postModel();
            $page = isset($postData['nowPage']) ? $postData['nowPage'] : 0;
            $postList = $postModel->userGroupPost($postData['userId'], $postData['groupId'], $page);
            $data = [];
            $data['userInfo'] = $userInfo ? $userInfo : array();
            $data['groupInfo'] = $groupInfo ? $groupInfo : array();
            $data['postList'] = $postList ? $postList : array();
            $result = array(
                'status' => 1,
                'data' => $data,
                'code' => 0,
            );
        } else {
            $result = array(
                'status' => 0,
                'data' => 'param error',
                'code' => 1,
            );
        }
        echo json_encode($result);
        exit;
    }

    /**
     * 获取用户余额
     * @author
     */
    public function getUserBalance()
    {
        $postData = $this->requestData;
        if (isset($postData['userId']) && $postData['userId'] > 0 && isset($postData['currencyId']) && $postData['currencyId'] > 0) {
            $cuModel = new UsersCurrencyModel();
            $tokenNum = $cuModel->getUserTokenNum($postData['userId'], $postData['currencyId']);
            $result = array(
                'status' => 1,
                'data' => $tokenNum ? $tokenNum : 0,
                'code' => 0,
            );
        } else {
            $result = array(
                'status' => 0,
                'data' => 'param error',
                'code' => 1,
            );
        }
        echo json_encode($result);
        exit;
    }

    /**
     * 创建钱包
     * @author
     */
    public function sendRedPacket()
    {
        $postData = $this->requestData;
        if (isset($postData['userId']) && $postData['userId'] > 0 && isset($postData['password']) && isset($postData['type']) && isset($postData['money']) && isset($postData['num'])) {
            $isRight = $this->userModel->verifyPassword($postData['userId'], $postData['password']);
            if ($isRight) {
                $cuModel = new UsersCurrencyModel();
                $tokenNum = $cuModel->getUserTokenNum($postData['userId'], $postData['currencyId']);
                if ($tokenNum >= $postData['money']) {
                    $redModel = new redModel();
                    $createRes = $redModel->createRedPacket($postData['userId'], $postData['money'], $postData['num'], $postData['type'], $postData['content'], $postData['currencyId']);
                    if ($createRes) {
                        $result = array(
                            'status' => 1,
                            'data' => 'create success',
                            'code' => 0,
                        );
                    } else {
                        $result = array(
                            'status' => 0,
                            'data' => 'create failed',
                            'code' => 6,
                        );
                    }
                } else {
                    $result = array(
                        'status' => 0,
                        'data' => 'balance not enough',
                        'code' => 5,
                    );
                }
            } else {
                $result = array(
                    'status' => 0,
                    'data' => 'password error',
                    'code' => 4,
                );
            }
        } else {
            $result = array(
                'status' => 0,
                'data' => 'param error',
                'code' => 1,
            );
        }
        echo json_encode($result);
        exit;
    }

    /**
     * 我的红包
     * @author
     */
    public function getMyRed()
    {
        $postData = $this->requestData;
        if (isset($postData['userId']) && $postData['userId'] > 0) {
            $page = isset($postData['nowPage']) ? $postData['nowPage'] : 0;
            $redModel = new redModel();
            $myRed = $redModel->myRedPacket($postData['userId'], $page);
            $result = array(
                'status' => 1,
                'data' => $myRed ? $myRed : [],
                'code' => 0,
            );
        } else {
            $result = array(
                'status' => 0,
                'data' => 'param error',
                'code' => 1,
            );
        }
        echo json_encode($result);
        exit;
    }


    /**
     * 红包信息
     * @author
     */
    public function redInfo()
    {
        $postData = $this->requestData;
        if (isset($postData['redId']) && $postData['redId'] > 0) {
            $page = isset($postData['nowPage']) ? $postData['nowPage'] : 0;
            $redModel = new redModel();
            $redInfo = $redModel->redInfo($postData['redId']);
            $redLogModel = new redLogModel();
            $getList = $redLogModel->getList($postData['redId'], $page);
            $data['redInfo'] = $redInfo;
            $data['getList'] = $getList;
            $result = array(
                'status' => 1,
                'data' => $data,
                'code' => 0,
            );
        } else {
            $result = array(
                'status' => 0,
                'data' => 'param error',
                'code' => 1,
            );
        }
        echo json_encode($result);
        exit;
    }


    /**
     * 我的邀请
     * @author
     */
    public function myInvitList()
    {
        $postData = $this->requestData;
        if (isset($postData['invit'])) {
            $page = isset($postData['nowPage']) ? $postData['nowPage'] : 0;
            $invitList = $this->userModel->getInvitList($postData['invit'], $page);
            $invitCount = $this->userModel->getInvitCount($postData['invit']);
            $data['list'] = $invitList;
            $data['count'] = $invitCount;
            $result = array(
                'status' => 1,
                'data' => $data,
                'code' => 0,
            );
        } else {
            $result = array(
                'status' => 0,
                'data' => 'param error',
                'code' => 1,
            );
        }
        echo json_encode($result);
        exit;
    }

    /**
     * 获取用户资金列表
     * @author
     */
    public function myCurrencyList()
    {
        $postData = $this->requestData;
        if (isset($postData['userId']) && $postData['userId'] > 0) {
            $userCurrencyModel = new UsersCurrencyModel();
            $type = isset($postData['type']) ? $postData['type'] : 0;
            $page = isset($postData['nowPage']) ? $postData['nowPage'] : 0;
            $currencyList = $userCurrencyModel->getUserCurrencyList($postData['userId'], $type, $page);
            $result = array(
                'status' => 1,
                'data' => $currencyList,
                'code' => 0,
            );
        } else {
            $result = array(
                'status' => 0,
                'data' => 'param error',
                'code' => 1,
            );
        }
        echo json_encode($result);
        exit;
    }

    /**
     * 获取账户余额
     * @author
     */
    public function getMyCuerrencySum()
    {
        $postData = $this->requestData;
        if (isset($postData['userId']) && $postData['userId'] > 0) {
            $userCurrencyModel = new UsersCurrencyModel();
            $currencyPriceSum = $userCurrencyModel->getUserCurrencySum($postData['userId']);
            $result = array(
                'status' => 1,
                'data' => $currencyPriceSum,
                'code' => 0,
            );
        } else {
            $result = array(
                'status' => 0,
                'data' => 'param error',
                'code' => 1,
            );
        }
        echo json_encode($result);
        exit;
    }

    /**
     * 获取用户钱包地址
     * @author
     */
    public function getCurrencyAddress()
    {
        $postData = $this->requestData;
        if (isset($postData['userId']) && $postData['userId'] > 0 && isset($postData['currencyId']) && $postData['currencyId'] > 0) {
            $userCurrencyModel = new UsersCurrencyModel();
            $userCurrencyAddress = $userCurrencyModel->getUserCurrencyAddress($postData['currencyId'], $postData['userId']);
            if ($userCurrencyAddress) {
                $result = array(
                    'status' => 1,
                    'data' => $userCurrencyAddress,
                    'code' => 0,
                );
            } else {
                $result = array(
                    'status' => 0,
                    'data' => 'no address',
                    'code' => 2,
                );
            }
        } else {
            $result = array(
                'status' => 0,
                'data' => 'param error',
                'code' => 1,
            );
        }
        echo json_encode($result);
        exit;
    }

    public function testUsdt()
    {
        //dump($this->userModel->getYqCode());
        //exit;
        $bitcoin = new Bitcoin('abcblock', 'abc123456');
        dump($bitcoin->omni_listtransactions('n126bCNq1dHi88YLyrZnsisZjAdicxS8sn', 100, 0, 1456997));
    }

}
